package com.joe.dev.springlearn.springmybatis.util;

import com.joe.dev.springlearn.springmybatis.annotation.JoeMapperScan;
import com.joe.dev.springlearn.springmybatis.dao.OrderMapper;
import com.joe.dev.springlearn.springmybatis.dao.UserMapper;
import org.mybatis.spring.mapper.ClassPathMapperScanner;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Map;
import java.util.Set;

public class JoeBeanDefinitionResitar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        Map<String, Object> annotationAttributes = annotationMetadata.getAnnotationAttributes(JoeMapperScan.class.getName());
        System.out.println(annotationAttributes.get("value")); // com.joe.dev.springlearn.springmybatis.dao

        AnnotationAttributes mapperScanAttrs = AnnotationAttributes
                .fromMap(annotationMetadata.getAnnotationAttributes(JoeMapperScan.class.getName()));
        System.out.println(annotationAttributes.get("value"));  // com.joe.dev.springlearn.springmybatis.dao
        // 获取包下所有的 mapper类，for循环添加到bd中，注入到spring中

        /*ClassPathMapperScanner scanner = new ClassPathMapperScanner(beanDefinitionRegistry);
        Set<BeanDefinitionHolder> value = scanner.doScan(annotationAttributes.get("value").toString());
        System.out.println(value);*/


        // 将UserMapper绑定到 bd JoeFactoryBean注入到 Spring
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder
                .genericBeanDefinition()
                .getBeanDefinition();
        // 将JoeFactoryBean 添加到bd
        beanDefinition.setBeanClassName(JoeFactoryBean.class.getName());
        beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(UserMapper.class);
        beanDefinitionRegistry.registerBeanDefinition("userMapper", beanDefinition);

        // 将OrderMapper绑定到 bd JoeFactoryBean注入到 Spring
        AbstractBeanDefinition beanDefinition1 = BeanDefinitionBuilder
                .genericBeanDefinition()
                .getBeanDefinition();
        beanDefinition1.setBeanClassName(JoeFactoryBean.class.getName());
        beanDefinition1.getConstructorArgumentValues().addGenericArgumentValue(OrderMapper.class);
        beanDefinitionRegistry.registerBeanDefinition("orderMapper", beanDefinition1);

    }
}
